"""
@Author    : ghenyar
@Time      : 2025/9/3 17:34
@File      : menus
@Desc      : 
"""

from typing import Optional

from pydantic import BaseModel, field_validator
from pydantic_core.core_schema import ValidationInfo

from app.common.tools import format_datetime
from app.models.menu_model import MenuModel


class MenuSchema(BaseModel):
    id: Optional[int] = None
    label: str
    name: Optional[str] = None
    p_id: int
    types: int
    code: Optional[str] = None
    e_link: int
    url: Optional[str] = None
    is_hide: int
    icon: Optional[str] = None
    sort: int

    @field_validator("types")
    def types_validator(cls, v: int) -> Optional[int]:
        if v is None or v == "":
            raise ValidationException("请选择类型")
        return v

    @field_validator("label")
    def validate_account(cls, v: str) -> Optional[str]:
        """验证菜单标题"""
        if v is None or v == "":
            raise ValidationException("标题不能为空")
        return v

    @field_validator("p_id")
    def validate_parent_id(cls, v: int) -> Optional[int]:
        """父级菜单"""
        if v is None:
            raise ValidationException("请选择上级菜单")
        return v

    @field_validator("code")
    def validate_code(cls, v, info: ValidationInfo):
        types = info.data.get("types")
        if types != 1 and (v is None or v == ""):
            raise ValidationException("权限码不能为空")
        return v

class MenuSerialize(BaseModel):
    """序列化菜单数据"""
    id: int
    label: str
    name: Optional[str] = None
    p_id: int
    parent: str
    code: Optional[str] = None
    e_link: int
    url: Optional[str] = None
    hide_menu: int
    types: int
    icon: Optional[str] = None
    sort: int
    created_at: str

    @classmethod
    async def from_orm (cls, obj: MenuModel):
        return cls(
            id = obj.id,
            label = obj.label,
            name =getattr(obj,"name",None),
            p_id = obj.p_id,
            parent = obj.p_label,
            code = getattr(obj,"code",None),
            e_link = obj.e_link,
            url = getattr(obj,"url",None),
            hide_menu = obj.is_hide,
            types = obj.types,
            icon = getattr(obj,"icon",None),
            sort = obj.sort,
            created_at = format_datetime(obj.created_at),
        )